package com.youboy.oauth;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.youboy.oauth.model.OAuthConsumerAuthentication;
import com.youboy.oauth.token.InvalidTokenException;
import com.youboy.oauth.token.OAuthToken;

/**
 * 
 * @author loudyn
 * 
 */
public abstract class OAuthProtectedResourceFilter extends OAuthProcessFilterSupport {

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.youboy.oauth.OAuthProcessFilterSupport#validateOAuthConsumerAuthentication(com.youboy.oauth.model.
	 * OAuthConsumerAuthentication)
	 */
	@Override
	protected void validateOAuthAuthentication(OAuthConsumerAuthentication consumerAuthentication) throws Exception {
		super.validateOAuthAuthentication(consumerAuthentication);

		String token = consumerAuthentication.getOAuthConsumerCredentials().getToken();
		OAuthToken oauthToken = getOAuthToken(token);
		if (null == oauthToken) {
			throw new InvalidTokenException(String.format("the oauthToken(%s) is not exist!", token));
		}

		if (!oauthToken.isAccessToken()) {
			throw new InvalidTokenException(String.format("the oauthToken(%s) is not a accessToken!", token));
		}

		String consumerKey = consumerAuthentication.getOAuthConsumerCredentials().getConsumerKey();
		if (!StringUtils.equals(consumerKey, oauthToken.getConsumerKey())) {
			throw new InvalidTokenException("the accessToken's consumerKey didn't match consumer'key!");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.youboy.oauth.OAuthProcessFilterSupport#onValidOAuthAuthenticate(com.youboy.oauth.model.
	 * OAuthConsumerAuthentication, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
	 * javax.servlet.FilterChain)
	 */
	@Override
	protected void onValidOAuthAuthentication(OAuthConsumerAuthentication consumerAuthentication, HttpServletRequest request,
											HttpServletResponse response, FilterChain chain) throws Exception {

		chain.doFilter(request, response);
	}

	private OAuthToken getOAuthToken(String token) {
		return getTokenService().getOAuthToken(token);
	}
}
